import {callFileSelect, CANCELED} from "./localFileSelect";
import {DetectedLog, LoadedData} from "../../common/types";
import path from "path";
import fs from "fs";

export const loadData = async ()=>{
    const filePath = await callFileSelect([{name:"Video",extensions:["mp4"]}]);
    if(filePath==CANCELED){
        throw new Error("USER CANCELED");
    }
    const res:LoadedData = {
        videoPath:filePath,
        detectedLog:[],
        fps:0,
        size:[]
    }
    const dirPath = path.dirname(filePath);
    const fileNamePrefix = path.basename(filePath, path.extname(filePath)); // 获取文件名作为前缀（不包括扩展名）
    const files:string[] = fs.readdirSync(dirPath);
    const jsonFiles = files.filter(file =>
        file.startsWith(fileNamePrefix+"_") && path.extname(file) === '.json'
    ).map(file => path.join(dirPath, file));
    for (const jsonFilePath of jsonFiles) {
        const rawData = fs.readFileSync(jsonFilePath, 'utf8'); // 读取文件内容
        const jsonData:{fps:number,logs:DetectedLog[],size:number[]} = JSON.parse(rawData); // 解析JSON数据
        res.detectedLog.push(...jsonData.logs);
        res.fps=jsonData.fps;
        res.size=jsonData.size
    }
    return res;
}
